﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace Dare.Utilities.IO
{
    public class FileMD5Serial
    {
        public static bool TryGetFileMD5Serial(string fileName, out string serial)
        {
            try
            {
                FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                serial = GetFileMD5Serial(fs);
                return true;
            }
            catch
            {
                serial = String.Empty;
                return false;
            }
        }

        public static string GetFileMD5Serial(string fileName)
        {
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            return GetFileMD5Serial(fs);
        }

        public static string GetFileMD5Serial(Stream stream)
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] md5byte = md5.ComputeHash(stream);
            int i, j;
            foreach (byte b in md5byte)
            {
                i = Convert.ToInt32(b);
                j = i >> 4;
                sb.Append(Convert.ToString(j, 16));
                j = ((i << 4) & 0x00ff) >> 4;
                sb.Append(Convert.ToString(j, 16));
            }
            stream.Close();
            stream.Dispose();
            return sb.ToString();
        }
    }
}
